package com.example.codereview.util;

import com.example.codereview.MyTextGutterIconRenderer;
import com.example.codereview.git.GitService;
import com.example.codereview.review.ReviewConstant;
import com.example.codereview.review.ReviewContent;
import com.intellij.ide.ui.LafManager;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Slf4j
public class IdeaUtils {

    private static GitService gitService = GitService.getInstance();

    public static String codeReviewPath(AnActionEvent e) {
        //模块路径
        String modulePath = IdeaUtils.getModuleFilePath(e);
        //模块分支名称
        String branchName = gitService.branchName(modulePath);
        if (branchName.contains("/")) {
            branchName = branchName.replaceAll("/", "-");
        }
        //代码评审路径
        return modulePath + ReviewConstant.REVIEW_DIR_PATH + "/" + branchName + ".ser";
    }

    public static String codeReviewPath(Project project, VirtualFile virtualFile) {
        //模块路径
        String modulePath = IdeaUtils.getModuleFilePath(project, virtualFile);
        //模块分支名称
        String branchName = gitService.branchName(modulePath);
        if (branchName == null) {
            return null;
        }
        if (branchName.contains("/")) {
            branchName = branchName.replaceAll("/", "-");
        }
        //代码评审路径
        return modulePath + ReviewConstant.REVIEW_DIR_PATH + "/" + branchName + ".ser";
    }

    public static String codeReviewPath(Module module) {
        //模块路径
        String modulePath = IdeaUtils.getModulePath(module);
        //模块分支名称
        String branchName = gitService.branchName(modulePath);
        if (branchName.contains("/")) {
            branchName = branchName.replaceAll("/", "-");
        }
        //代码评审路径
        return modulePath + ReviewConstant.REVIEW_DIR_PATH + "/" + branchName + ".ser";
    }

    public static String getModulePath(Module module) {
        VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots();
        // 假设一个模块只有一个内容根目录，你可以根据实际需求选择合适的目录
        if (contentRoots.length > 0) {
            return contentRoots[0].getPath();
        } else {
            return null; // 或者抛出异常，表明没有找到内容根目录
        }
    }

    public static String getModuleFilePath(AnActionEvent e) {
        Project project = e.getProject();
        if (!ObjectUtils.isEmpty(project)) {
            Module module = e.getData(LangDataKeys.MODULE);
            if (!ObjectUtils.isEmpty(module)) {
                return ModuleRootManager.getInstance(module).getContentRoots()[0].getPath();
            } else {
                return ProjectRootManager.getInstance(project).getContentRoots()[0].getPath();
            }
        }
        JOptionPaneUtils.warn("找不到项目或模块");
        throw new RuntimeException("找不到项目或模块");
    }


    public static String getModuleFilePath(Project project, VirtualFile virtualFile) {
        Module module = ModuleUtil.findModuleForFile(virtualFile, project);
        if (!ObjectUtils.isEmpty(module)) {
            return ModuleRootManager.getInstance(module).getContentRoots()[0].getPath();
        } else {
            return ProjectRootManager.getInstance(project).getContentRoots()[0].getPath();
        }
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }


    @SuppressWarnings("unchecked")
    public static <T> T parseObject(String name) {
        try (FileInputStream fileIn = new FileInputStream(name)) {
            ObjectInputStream in = new ObjectInputStream(fileIn);

            // 读取对象并打印信息
            return (T) in.readObject();
        } catch (Exception e) {
            log.error("{}文件不存在", name, e);
        }
        return null;
    }


    public static void writeObject(Object obj, String name) {
        File file = new File(name);
        if (file.exists()) {
            file.delete();
        }
        try (FileOutputStream fileOut = new FileOutputStream(name)) {
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            // 将对象序列化为字节流并写入文件
            out.writeObject(obj);
            System.out.println("Person object serialized and written to the file.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String createDir(String path) {
        File file = new File(path);
        if (!file.exists() && file.mkdir()) {
            return path;
        }
        return "";
    }

    public static void removeGutterIcon(Project project, int lineNumber) {
        Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor != null) {
            PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
            if (psiFile != null) {
                MarkupModel markupModel = editor.getMarkupModel();
                Document document = editor.getDocument();
                RangeHighlighter[] allHighlighters = markupModel.getAllHighlighters();
                for (RangeHighlighter highlighter : allHighlighters) {
                    int nowLine = document.getLineNumber(highlighter.getStartOffset());
                    GutterIconRenderer gutterIconRenderer = highlighter.getGutterIconRenderer();
                    if (lineNumber - 1 == nowLine && gutterIconRenderer instanceof MyTextGutterIconRenderer) {
                        markupModel.removeHighlighter(highlighter);
                    }
                }
            }
        }
    }

    public static void addGutterIcon(Project project, String content, int lineNumber, int status) {
        Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor != null) {
            PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
            if (psiFile != null) {
                MarkupModel markupModel = editor.getMarkupModel();
                Document document = editor.getDocument();
                RangeHighlighter[] allHighlighters = markupModel.getAllHighlighters();
                for (RangeHighlighter highlighter : allHighlighters) {
                    int nowLine = document.getLineNumber(highlighter.getStartOffset());
                    GutterIconRenderer gutterIconRenderer = highlighter.getGutterIconRenderer();
                    if (lineNumber - 1 == nowLine && gutterIconRenderer instanceof MyTextGutterIconRenderer) {
                        markupModel.removeHighlighter(highlighter);
                    }
                }
                RangeHighlighter highlighter = markupModel.addLineHighlighter(lineNumber - 1, 0, null);
                // 设置行高亮标记的 gutter 图标渲染器
                MyTextGutterIconRenderer renderer = new MyTextGutterIconRenderer("R", content, status, lineNumber);
                highlighter.setGutterIconRenderer(renderer);


            }
        }
    }

    /**
     * 查询鼠标选中的代码块
     */
    public static String getSelectCodeContent(AnActionEvent e) {
        // 获取当前活动的编辑器
        Editor editor = e.getData(PlatformDataKeys.EDITOR);
        if (editor != null) {
            // 获取编辑器的选择模型
            SelectionModel selectionModel = editor.getSelectionModel();
            // 检查是否已有选区
            if (selectionModel.hasSelection()) {
                // 获取并打印选中的文本
                return selectionModel.getSelectedText();
            }
        }
        return "";
    }


    public static void processJavaFileOpening(Project project, VirtualFile file) {
        // 在这里添加你的代码来处理Java文件打开时的操作，例如在行号区添加标记
        //代码评审路径
        String codeReviewPath = IdeaUtils.codeReviewPath(project, file);
        List<ReviewContent> reviewContents = IdeaUtils.parseObject(codeReviewPath);
        if (!ObjectUtils.isEmpty(reviewContents)) {
            for (ReviewContent content : reviewContents) {
                if (file.getPath().equals(content.getPath())) {
                    IdeaUtils.addGutterIcon(project, content.getAuthor() + ": " + content.getContent(), content.getNumber(), content.getStatus());
                }
            }
        }
    }

    public static String getTheme() {
        LafManager lafManager = LafManager.getInstance();
        UIManager.LookAndFeelInfo currentLookAndFeel = lafManager.getCurrentLookAndFeel();
        // 获取当前外观名称
        return currentLookAndFeel.getName();
    }


    public static List<String> codeSplit(String value) {
        List<String> values = Arrays.asList("{", "}", "(", ")", " ", ".", ",", ";", "=");
        List<String> codes = new ArrayList<>();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < value.length(); i++) {
            char c = value.charAt(i);
            String codeC = String.valueOf(c);
            if (values.contains(codeC)) {
                if (!ObjectUtils.isEmpty(builder.toString())) {
                    codes.add(builder.toString());
                    builder = new StringBuilder();
                }
                codes.add(codeC);
            } else {
                builder.append(codeC);
            }
        }
        if (!ObjectUtils.isEmpty(builder)) {
            codes.add(builder.toString());
        }
        return codes;
    }

    public static void main(String[] args) {
        Object o = parseObject("E:\\study_project\\code-review-plugin\\code-review\\1.0.8.ser");
        System.out.println();
    }
}
